<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\News;
use App\Model\NewsComment;
use App\Model\NewsJoin;
use App\Model\Notify;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\AdminApiAuth;
use Hyperf\DbConnection\Db;

use Hyperf\Di\Annotation\Inject;
use App\Service\NotifyQueueService;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class NewsController extends AppBaseController
{

    #[Inject] protected NotifyQueueService $notifyQueueService;


    /**
     * 后台--资讯、学习|列表
     * @param int $type  -1：全部  1：资讯新闻 2：学习发布
     * @return object
     */
    #[RequestMapping(path:'newsList/{type}',methods: 'get')]
    public function newsList(int $type = -1): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 10);
            $offset = ($page - 1) * $limit;

            $where = [];
            if($type==-1){
                $whereIn = [1,2];
            }else{
                $whereIn = [$type];
            }
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }

            $list = News::with(['party'=>function($query){
                    $query->selectRaw('id,name')->first();
                }])
                ->where($where)
                ->whereIn('type',$whereIn)
                ->selectRaw('id,party_id,type,title,status,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            $total = 0;
            if($list->isNotEmpty()){
                if($page==1){
                    $total = News::where($where)->whereIn('type',$whereIn)->count();
                }
                if(count($list)>=$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next, 'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--资讯、学习|详情
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path:'newsInfo/{news_id}',methods: 'get')]
    public function newsInfo(int $news_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $info = News::where('id',$news_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 后台--资讯、学习|编辑
     * @param int|null $news_id
     * @return object
     */
    #[RequestMapping(path: 'newsEdit[/{news_id}]',methods: 'post,get')]
    public function newsEdit(int|null $news_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //获取所有参数
            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['type'] = 1;
//                $data['party_id'] = 1;
//                $data['title'] = '12312312321312';
//                $data['photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['link_url'] = 'https://www.baidu.com';
//                $data['is_banner'] = 1;
//                $data['banner_photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['content'] = '学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习';
//                $data['file_list'] = [
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com'],
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com']
//                ];
//                $data['is_long'] = 0;
//                $data['show_start_at'] = '2024-09-01 12:12:12';
//                $data['show_end_at'] = '2024-09-01 12:12:12';
//                $data['status'] = 1;
//            }
            //虚拟数据

            if(empty($data['type']) || !in_array($data['type'],[1,2])
                || empty($data['title'])
            ){
                return $this->reMsg->re(10007);
            }

//            if(empty($data['banner_photo'])) return $this->reMsg->re(10007);
            if(empty($data['content'])) $data['content'] = null;
            if(empty($data['file_list'])|| !is_array($data['file_list'])) $data['file_list'] = [];
            if(isset($data['is_long']) && $data['is_long']==0){
                if((empty($data['show_start_at']) || empty($data['show_end_at']))) return $this->reMsg->re(10007);
            }else{
                $data['is_long'] = 1;
                $data['show_start_at'] = null;
                $data['show_end_at'] = null;
            }

            empty($data['is_banner']) || !is_numeric($data['is_banner']) ? $data['is_banner'] = 0 : $data['is_banner'] = 1;
            empty($data['is_show']) || !is_numeric($data['is_show']) ? $data['is_show'] = 0 : $data['is_show'] = 1;
            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;

            //不指定支部
            if($_admin->level==1){
//                if(!isset($data['party_id']) || $data['party_id']==null) return $this->reMsg->re(10007);
//                $party_id = $data['party_id'];
                $party_id = $_admin->party_id;
            }else{
                $party_id = $_admin->party_id;
            }

            if($news_id){
                //编辑
                $info = News::where('id',$news_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);

                //判断是否有权操作(特殊)
                if($_admin->level!=1 && $_admin->id!=$info->admin_id) return $this->reMsg->re(10009);

                $info->title = $data['title'];
                $info->photo = $data['photo'];
                $info->link_url = $data['link_url'];
                $info->content = $data['content'];
                $info->file_list = $data['file_list'];
                $info->is_banner = $data['is_banner'];
                $info->banner_photo = $data['banner_photo'];
                $info->is_long = $data['is_long'];
                $info->show_start_at = $data['show_start_at'];
                $info->show_end_at = $data['show_end_at'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = News::create($data);
                if($insertRet){
                    //执行消息队列任务
                    $this->notifyQueueService->pushNews(['id'=>$insertRet->id],3);
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--资讯、学习|删除
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path: 'newsDelete/{news_id}',methods: 'get')]
    public function newsDelete(int $news_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $info = News::where('id',$news_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限
            if($_admin->level!=1 && $_admin->id!=$info->admin_id) return $this->reMsg->re(10009);
            $info->delete();
            //同时删除自己的关联 - 通知
            $notifyWhere['module'] = 1; //资讯
            $notifyWhere['relation_id'] = $info->id;
            Notify::where($notifyWhere)->delete();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 资讯学习列表
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path:'newsJoinList/{news_id}',methods: 'get')]
    public function newsJoinList(int $news_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['news_id'] = $news_id;
            $list = NewsJoin::with(['user'=>function($query){
                    $query->selectRaw('id,nickname,avatar,auth_name')->get();
                }])
                ->selectRaw('id,uid,created_at')
                ->where($where)
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = NewsJoin::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 资讯评论列表
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path:'newsCommentList/{news_id}',methods: 'get')]
    public function newsCommentList(int $news_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['news_id'] = $news_id;
            $list = NewsComment::with(['user'=>function($query){
                    $query->selectRaw('id,nickname,avatar,auth_name')->get();
                }])
                ->selectRaw('id,uid,content,created_at')
                ->where($where)
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = NewsComment::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }





}